<script setup>
import {examListService,uploadStudentAnswerService} from '@/api/student.js'
import dayjs from 'dayjs';

import { ElMessage } from 'element-plus'
import { ref } from 'vue'
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);  
dayjs.extend(timezone);
import { useRouter } from 'vue-router';
const router = useRouter();
const fileList = ref([]);
const searchForm = ref({
    e_name: '',
});
let isUpdating = ref(false); 
const page = ref({
    pageNum: 1, //当前页
    pageSize: 5, //每页条数
})

const examData = ref([
    {
    e_id: 1,         // 考试 ID（新增考试时为空）
    e_name: '',         // 考试名称
    startTime: null,    // 考试开始时间
    endTime: null,      // 考试结束时间
    to_endTime: null,   //距离结束的时间
    e_autostart: 0, // 是否自动开始
    fileBase64: '',
    fileName: '',  
    total: '',
    status: '',  
    teacher_id: '',
}]);

const formatDate=(dateString) =>{
    return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss');
    }

const searchExam =async ()=>{
    const { e_name} = searchForm.value;
    let params = {
        pageNum: page.value.pageNum,
        pageSize: page.value.pageSize,
        examName: e_name,
    }
    console.log(params)

 
        try{  
    let result = await examListService(params);
    examData.value = result.data.list.map(item => ({
            e_id: item.id,
            e_name: item.examName,  // 映射examName到e_name
            startTime: item.beginTime,  // 映射beginTime到startTime
            endTime: item.endTime,
            status: item.status,
            fileName: item.fileName,
            fileBase64: item.fileBase64,
            e_autostart: item.auto,
            teacher_id: item.teacherId,
            to_endTime: calculateTimeRemaining(item.endTime, item.beginTime,item.status,item.id),  
        }));
    examData.value.total=result.data.total;
    }catch(error){
        console.error('Error in exam list request:', error);
    }

};

const calculateTimeRemaining = (endTime,startTime,status,id) => {
    // 获取当前时间
    const currentTime = new Date();

    // 将结束时间转换为 Date 对象
    const endDate = new Date(endTime);
    
    const startDate = new Date(startTime);

    // 计算时间差，返回的是毫秒数
    const timeDiff = endDate - currentTime;

    if (timeDiff <= 0) {
        return "已结束";  // 如果结束时间小于当前时间，说明考试已经结束
    }
    if(currentTime<startDate){
        return "未开始";
    }

    if (status === "未开始" &&! isUpdating.value &&id !== undefined) {
        handleExamUpdate(id)
        examList();
    }

    // 计算剩余天数、小时数、分钟数和秒数
    const days = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeDiff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeDiff % (1000 * 60)) / 1000);

    // 返回格式化的时间
    return `${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;
};

const onCurrentChange = (num) => {
    page.value.pageNum = num
    examList();
}

const examList = async () => {
    let params = {
        pageNum: page.value.pageNum,
        pageSize: page.value.pageSize,
        examName: '',
    }
    try{  
    let result = await examListService(params);
    examData.value = result.data.list.map(item => ({
            e_id: item.id,
            e_name: item.examName,  // 映射examName到e_name
            startTime: item.beginTime,  // 映射beginTime到startTime
            endTime: item.endTime,
            status: item.status,
            fileName: item.fileName,
            fileBase64: item.fileBase64,
            e_autostart: item.auto,
            teacher_id: item.teacherId,
            to_endTime: calculateTimeRemaining(item.endTime, item.beginTime,item.status,item.id),  
        }));
    examData.value.total=result.data.total;

     
    }catch(error){
        console.error('Error in exam list request:', error);
    }
}
examList();

// 调用 examList 获取数据并启动倒计时
examList().then(() => {
    startCountdown();  // 启动定时器
});

const startCountdown = () => {
    const updateCountdown = () => {
        examData.value.forEach(item => {
            item.to_endTime = calculateTimeRemaining(item.endTime, item.startTime,item.status,item.id);
        });
        requestAnimationFrame(updateCountdown); // 下一帧继续更新
    };
    updateCountdown(); // 启动循环
};


const getDownloadUrl = (base64Data) => {
      const byteCharacters = atob(base64Data);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: 'application/octet-stream' });
      return URL.createObjectURL(blob);
    };

    const handleFileChange = (file) => {
  fileList.value = [...fileList.value, file];
};
const uploadAnswer = (row) => {
    try {
        // 组织 exam 数据，映射字段名
        const uploadAnswerData = {
            id: row.e_id,
            examName: row.e_name,
            teacherId: row.teacher_id
        };
        // 创建 FormData 对象
        const formData = new FormData();
        formData.append('exam', new Blob([JSON.stringify(uploadAnswerData)],{type: 'application/json'}));

        if(fileList.value.length){
          fileList.value.forEach(file => {
    formData.append('file', file.raw);
  });
        }
        // 调用服务更新考试信息
        uploadStudentAnswerService(formData).then(() => {
            ElMessage.success('上传成功');
        })
        .catch(() => {
        ElMessage.error('上传失败');
        });
    } catch (error) {
        // 处理错误
    }
};

</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>我的考试</span>
            </div>
        </template>

        <!-- 根据考试名称查询某场考试or新增考试信息 -->
        <el-form :model="searchForm" inline style="margin-bottom: 20px">
            <el-form-item label="考试名称">
                <el-input v-model="searchForm.e_name" placeholder="请输入考试名称" clearable />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="searchExam">查询</el-button>
            </el-form-item>
        </el-form>

        <!-- 考试列表 -->
        <el-table :data="examData" style="width: 100%" >
            <el-table-column label="名称">
                <template #default="{ row }">{{ row.e_name }}</template>
            </el-table-column>
            <el-table-column label="开始时间">
                <template #default="{ row }">{{ formatDate(row.startTime) }}</template>
            </el-table-column>
            <el-table-column label="结束时间">
                <template #default="{ row }">{{ formatDate(row.endTime) }}</template>
            </el-table-column>
            <el-table-column label="距离结束时间">
                <template #default="{ row }">{{ row.to_endTime }}</template>
            </el-table-column>
            <el-table-column label="试卷">
                <template #default="{ row }">
                <div v-if="row.fileBase64">
                <a  @click.stop :href="getDownloadUrl(row.fileBase64)" :download="row.fileName" class="file-link">
                    {{ row.fileName }}
                 </a>
                </div>
                <div v-else>
                 <span>暂无文件</span>
             </div>
            </template>
            </el-table-column>
            <el-table-column label="答卷">
                <template #default="{ row }">
        <el-row>
          <el-col :span="1.5">
            <el-upload
              class="upload-demo"
              action="#"
              :on-change="handleFileChange"
              :file-list="fileList" 
              :auto-upload="false"
            >
              <el-button type="warning" icon="Upload">选择文件</el-button>
            </el-upload>
          </el-col>

          <!-- 显示文件列表 -->
          

          <!-- 导入按钮 -->
          <el-col :span="1.5">
            <el-button type="primary" @click="uploadAnswer(row)">上传答卷</el-button>
          </el-col>
        </el-row>
      </template>
            </el-table-column>

            <template #empty>
                <el-empty description="没有考试数据" />
            </template>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                background
                layout="total, prev, pager, next, jumper"
                :total="examData.total"
                :page-size.sync="page.pageSize"
                :current-page.sync="page.pageNum"
                @current-change="onCurrentChange"
            />
            <span class="fixed-size-info">每页5条</span>
        </div>

    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-form-item {
        margin-bottom: 10px;
    }

    .status-blue {
        color: rgb(26, 154, 214);
    }

    .status-green {
        color: rgb(26, 223, 118);
    }

    .status-red {
        color: rgb(234, 15, 15);
    }
    .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;  /* 居中对齐 */
    align-items: center;      /* 垂直居中对齐 */
}

.fixed-size-info {
    margin-left: 16px;
    font-size: 14px;
    color: #606266; 
    display: inline-block;  /* 确保它和分页控件在同一行 */
}
}
</style>